<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--订单数据-->
      <el-col :span="24" :xs="24">

        <!-- 搜索 -->
        <template>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input
                v-model="queryParams.orderNo"
                placeholder="请输入订单编号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="PK状态" prop="pkStatus">
              <el-select
                v-model="queryParams.pkStatus"
                placeholder="PK状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.app_pk_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否结算" prop="isSettle">
              <el-select
                v-model="queryParams.isSettle"
                placeholder="是否结算"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
              <el-input
                v-model="queryParams.shopId"
                placeholder="请输入店铺ID"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </template>

        <!-- 按钮操作栏 -->
        <template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['order:pk:add']"
              >新增</el-button>
            </el-col>
          </el-row>
        </template>

        <!-- 表格 -->
        <template>
          <el-table v-loading="loading" :data="orderPkList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="订单编号" align="center" key="orderNo" prop="orderNo" width="230" />
            <el-table-column label="发起店员" align="center" key="startUserId" prop="startUserId" :show-overflow-tooltip="true" width="150" >
              <template slot-scope="scope">
                <div class="flex-align-center" v-if="scope.row.startUserInfo">
                  <el-avatar shape="circle" size="medium" :src="scope.row.startUserInfo.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14 width-60 ellipsis tleft">{{scope.row.startUserInfo.nickName}}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="接受店员" align="center" key="employeeUserId" prop="employeeUserId" :show-overflow-tooltip="true" min-width="150" >
              <template slot-scope="scope">
                <div class="flex-align-center" v-if="scope.row.acceptUserInfo">
                  <el-avatar shape="circle" size="medium" :src="scope.row.acceptUserInfo.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14 width-60 ellipsis tleft">{{scope.row.acceptUserInfo.nickName}}</div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="PK时长(小时)" align="center" key="pkTime" prop="pkTime" width="130" sortable="custom" :sort-orders="['descending', 'ascending']" :show-overflow-tooltip="true" />
            <el-table-column label="PK状态" align="center" key="pkStatus" prop="pkStatus" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.app_pk_status" :value="scope.row.pkStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="发起用户完成金额" align="center" key="startUserAmount" prop="startUserAmount" :show-overflow-tooltip="true" />
            <el-table-column label="发起用户达标金额" align="center" key="startUserThreshold" prop="startUserThreshold" :show-overflow-tooltip="true" />
            <el-table-column label="接受用户完成金额" align="center" key="acceptUserAmount" prop="acceptUserAmount" :show-overflow-tooltip="true" />
            <el-table-column label="接受用户达标金额" align="center" key="acceptUserThreshold" prop="acceptUserThreshold" :show-overflow-tooltip="true" />
            <el-table-column label="开始时间" align="center" prop="pkStartTime" sortable="custom" :sort-orders="['descending', 'ascending']" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.pkStartTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="pkEndTime" sortable="custom" :sort-orders="['descending', 'ascending']" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.pkEndTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" :sort-orders="['descending', 'ascending']" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" prop="shopInfo.shopName" min-width="120" v-if="$store.getters && $store.getters.admin" />
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="120"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row,scope.index)"
                  v-hasPermi="['order:pk:list']"
                >详细</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['order:pk:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </template>

      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <template>
      <!-- 添加或修改订单配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="900px" :close-on-click-modal="false" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="选择发起店员" prop="startUserId">
                <div class="flex-align-center">
                  <div class="mgr5" v-if="form.startUserInfo && form.startUserInfo.nickName">{{ form.startUserInfo.nickName }}</div>
                  <el-image style="width: 100px; height: 100px" :src="form.startUserInfo.avatar" fit="fill" class="mgr10" v-if="form.startUserInfo && form.startUserInfo.avatar"></el-image>
                  <el-button type="primary" @click="handleSelectEmployee('start_user')">选择店员</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择接受店员" prop="acceptUserId">
                <div class="flex-align-center">
                  <div class="mgr5" v-if="form.acceptUserInfo && form.acceptUserInfo.nickName">{{ form.acceptUserInfo.nickName }}</div>
                  <el-image style="width: 100px; height: 100px" :src="form.acceptUserInfo.avatar" fit="fill" class="mgr10" v-if="form.acceptUserInfo && form.acceptUserInfo.avatar"></el-image>
                  <el-button type="primary" @click="handleSelectEmployee('accept_user')">选择店员</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 选择店员对话框 -->
      <el-dialog title="选择店员" :visible.sync="employeeOpen" width="800px" :close-on-click-modal="false" append-to-body>
        <el-table v-loading="loading" :data="employeeList">
            <el-table-column type="index"  label="序号" />
            <el-table-column label="店员" align="center" key="nickName" width="150" prop="userId" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <div class="flex-align-center">
                  <el-avatar shape="circle" size="medium" :src="scope.row.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14 width-60 ellipsis tleft">{{scope.row.nickName}}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="等级" align="center" key="userLevel" prop="userLevel" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.levelInfo.levelTitle }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="160"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleSubmitEmployee(scope.row)"
                >确定</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="employeeTotal > 0"
            :total="employeeTotal"
            :page.sync="queryEmployeeParams.pageNum"
            :limit.sync="queryEmployeeParams.pageSize"
            @pagination="getEmployeeList"
          />
      </el-dialog>
    </template>
  </div>
</template>

<script>
import { listOrderPk, getOrderPk, delOrderPk, addOrderPk, updateOrderPk, changeOrderPkStatus } from "@/api/order/pk";
import { listUser } from "@/api/employee/user";
export default {
  name: "OrderPk",
  dicts: ['sys_normal_disable', 'app_order_status', 'sys_yes_no', 'app_pk_status'],
  components: { },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderPkList: null,
      // 店员表格数据
      employeeList: null,
      // 总条数
      employeeTotal: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      employeeOpen: false,
      selectUserType: '',
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pkStatus: undefined,
        orderNo: undefined,
        isSettle: undefined,
        shopId: undefined,
        orderByColumn: 'createTime',
        isAsc: 'descending',
      },
      // 查询参数
      queryEmployeeParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'userLevel',
        isAsc: 'descending',
      },
      // 表单校验
      rules: {
        pkTitle: [
          { required: true, message: "订单名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '订单名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrderPk(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.orderPkList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },/** 查询店员列表 */
    getEmployeeList() {
      listUser(this.addDateRange(this.queryEmployeeParams)).then(response => {
          this.employeeList = response.rows;
          this.employeeTotal = response.total;
          this.employeeOpen = true
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderNo: undefined,
        isSettle: undefined,
        pkTime: undefined,
        startUserId: undefined,
        acceptUserId: undefined,
        pkStatus: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderNo);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getOrderPk().then(response => {
        this.open = true;
        this.title = "添加订单";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderNo = row.orderNo || this.ids;
      getOrderPk(orderNo).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          if (this.form.orderNo != undefined) {
            updateOrderPk(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderPk(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    handleSelectEmployee(type){
      this.selectUserType = type;
      this.getEmployeeList();
    },
    handleSubmitEmployee(row){
      this.employeeOpen = false;
      if(this.selectUserType === 'start_user'){
        this.form.startUserId = row.userId;
        this.form.startUserInfo = row;
      }
      if(this.selectUserType === 'accept_user'){
        this.form.acceptUserId = row.userId;
        this.form.acceptUserInfo = row;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderNos = row.orderNo || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderNos + '"的数据项？').then(function() {
        return delOrderPk(orderNos);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('orderPk/orderPk/export', {
        ...this.queryParams
      }, `orderPk_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
